%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>

static int tabstop = 2;

static void printspaces(int);
%}

%s COMMENT STRINGLITERAL ESCAPED

NL	("\n"|"\r\n")

%%

"\\(.|[\t\v\r\n])" { /* Firstly, handle escaped characters */
  ECHO;
 }

<INITIAL>^[ \t]+ { /* expand preceding whitespace */
  int i = 0;
  while (yytext[i]) {
    if (yytext[i] == '\t')
      printspaces(tabstop);
    else
      printspaces(1);
    i++;
  }
 }

<INITIAL>[ \t]+$ { /* kill trailing whitespace */ }

<INITIAL>"\"" {
  ECHO;
  BEGIN STRINGLITERAL;
 }
<STRINGLITERAL>"\"" {
  ECHO;
  BEGIN 0;
 }
<STRINGLITERAL>(.|{NL}) {
  ECHO;
 }

<INITIAL>"/*" {
  ECHO;
  BEGIN COMMENT;
 }
<COMMENT>(.|[ \t\v\r\n]|{NL}) {
  ECHO;
 }
<COMMENT>^[ \t]+ { /* expand preceding whitespace */
  int i = 0;
  while (yytext[i]) {
    if (yytext[i] == '\t')
      printspaces(tabstop);
    else
      printspaces(1);
    i++;
  }
 }

<COMMENT>"*/" {
  ECHO;
  BEGIN 0;
 }

<INITIAL>(.|{NL}) {
  ECHO;
 }

%%

int yywrap(void) { return 1; }

int main(int argc, char **argv) {
  if (argc == 2)
    tabstop = atoi(argv[1]);
  yylex();
  return 0;
}

void printspaces(int n) {
  int i;

  for (i = 0; i < n; i++) {
    putchar(' ');
  }
}
